Error Handling in Javascript


Published on: July 03, 2021 By T.Andrew Rayan

The error handling in javascript can be done using the try/catch block. The purpose of this try/catch block is to run set of codes which is suspected to throw some error.

In such cases, we will write those set of codes in the try block and handle the error in the catch block.

Syntax for try/catch block:

In the above syntax we can put the set of codes in the try block. Now the catch block will get the error as the parameter. The error parameter will have a property message in which we will receive the cause of error.

Example for try/catch block:

Output

count is not defined

In the above example, I didnt declare a variable with name count, but tried to use the variable in the try block. So it will throw an error. The error will be caught by the catch block and the error parameter will hold the error.

We can also manually throw an error using throw keyword. Lets see an example for it.

Example for throw error:

Output

Error: The value of count should be greater than 0

Here when the count variable value is less than 0, then we are throwing an error using the throw keyword and new error is created using new Error() syntax.

finally block:

The finally block is used to execute a block of code irrespective of try block or catch block execution. The finally block is used to perform any cleaning purpose. This will execute after the try or catch block execution.

Synatax for finally block:

Example for finally block:

Output:

Error: The value of count should be greater than 0 Program execution completed.

Here we had just added the finally block to the previous program. This program once after handling the error in catch block will call the finally block and execute those codes in it.


Most Read